import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_module/tabbar/shop/shop_row_widget.dart';
import 'package:flutter_module/tool/shopDeviceManager.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provider/provider.dart';
import 'areaModel.dart';
import 'shopScreenProvider.dart';
import 'shop_screen_area_provider.dart';

class ShopScreenArea extends StatefulWidget {
  @override
  _ShopScreenAreaState createState() => _ShopScreenAreaState();
}

class _ShopScreenAreaState extends State<ShopScreenArea> with AutomaticKeepAliveClientMixin {

  // 必须重写
  @override
  bool get wantKeepAlive => true;

  EasyRefreshController _controller;
  ScrollController _listController = ScrollController();

  bool _isBuild = false;

  @override
  void initState() { 
    super.initState();
    _controller = EasyRefreshController();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    _isBuild = false;

    print('build-----------------1');
    return MultiProvider(
      providers: [ChangeNotifierProvider.value(value: ShopScreenAreaProvider())],
      child: Column(
        children: <Widget>[
          shopHeaderWidget(context),
          shopListView(context)
        ],
      ),
    );
  }

  Widget shopHeaderWidget(BuildContext context){

    return Container(
      height: 70,
      color: Color.fromRGBO(235, 239, 244, 1),
      child: Container(
        color: Colors.white,
        margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Consumer2<ShopScreenAreaProvider,ShopScreenProvider>(
          builder: (context,provider,shopProvider,child){

            print('build-----------------2');
            List<AreaModel> list = provider.areaHeaderList;
            return ListView.builder(
              scrollDirection: Axis.horizontal,
              physics:  ClampingScrollPhysics(),
              itemCount: list.length,
              itemBuilder: (context,index){
                return shopHeaderItemWidget(list[index],index,(){
                  list.removeRange(index+1, list.length);
                  provider.reloadAreaHeaderList(list);

                  _listController.jumpTo(_listController.position.minScrollExtent);
                  AreaModel subAreaModel = list[index];
                  List<dynamic> subList = [];
                  subList.addAll(subAreaModel.children);
                  subList.addAll(subAreaModel.shops);
                  shopProvider.setAreaShop(subList);
                });
              },
            );
          },
        )
      )
    );
  }

  Widget shopHeaderItemWidget(AreaModel areaModel,int index,Function func){
    return Container(
      color: Colors.white,
      child: Center(
        child: Row(
          children: <Widget>[
            Offstage(
              offstage: index == 0 ? true : false,
              child: Image.asset('images/common_arrow_gray_right.png'),
            ),
            SizedBox(width: 10),
            InkWell(
              onTap: (){
                func();
              },
              child: Text('${areaModel.context.name}',style: TextStyle(color: Color.fromRGBO(46, 137, 250, 1))),
            ),
            SizedBox(width: 10),
          ],
        ),
      ),
    );
  }

  Widget shopListView(BuildContext context){

    return FutureBuilder(
      future: ShopDeviceManager.fetchAreaTree(),
      builder: (context,snapshot){

        if (!snapshot.hasData) {
          return Center(
            child: SpinKitCircle(color: Colors.lightBlue,),
          );
        }

        return Consumer2<ShopScreenProvider,ShopScreenAreaProvider>(
          builder: (context,provider,headerProvider,child){

            if (!_isBuild) {
              _isBuild = true;
              AreaModel rootAreaModel = snapshot.data;
              List<dynamic> areaShopList = [];
              areaShopList.addAll(rootAreaModel.children);
              areaShopList.addAll(rootAreaModel.shops);
              provider.setAreaShop(areaShopList);
              
              Future.delayed(Duration(seconds: 1), () {
                headerProvider.addAreaHeaderModel(rootAreaModel);
              });
            }
            

            List<dynamic> _list = provider.areaShops;
            if (_list.length == 0) {
              return Container(
                child: Center(child: Text('暂无数据')),
              );
            }

            print('build-----------------3');
            return Expanded(
              child: EasyRefresh(
                  controller: _controller,
                  enableControlFinishRefresh: true,
                  child: ListView.builder(
                    shrinkWrap: true,
                    controller: _listController,
                    itemCount: _list.length,
                    itemBuilder: (context, index) {
                      dynamic model = _list[index];
                      if (model is AreaModel) {
                        return areaWidget(model,(){
                          // ListView滚动到最上方
                          _listController.jumpTo(_listController.position.minScrollExtent);
                          AreaModel subAreaModel = model;
                          List<dynamic> subList = [];
                          subList.addAll(subAreaModel.children);
                          subList.addAll(subAreaModel.shops);
                          provider.setAreaShop(subList);

                          headerProvider.addAreaHeaderModel(model);
                        });
                      } else {
                        return ShopRowWidget(model:model);
                      }
                      
                    },
                ),
                onRefresh: () async {
                  await Future.delayed(Duration(seconds: 2), () {
                    ShopDeviceManager.fetchAreaTree().then((value){
                      print(value);
                      _controller.finishRefresh();
                    });
                  });
                  
                },
              )
            );
          },
        );

      },
    );
  }

   Widget areaWidget(AreaModel areaModel,Function fun){

    return InkWell(
      onTap: (){
        fun();
      },
      child: Container(
        height: 60,
        color: Colors.white,
        margin: EdgeInsets.only(bottom: 2.5),
        child: Flex(
          direction: Axis.horizontal,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            SizedBox(width: 15),
            Expanded(
              child: Text(
                areaModel.context.name,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Text('[${areaModel.children.length}]',style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1))),
            SizedBox(width: 10),
            Padding(
              padding: EdgeInsets.only(right: 15),
              child: Image.asset('images/common_arrow_gray_right.png'),
            )
          ],
        ),
      ),
    );
  }

}